<template>
  <view class="auth-page">
    <ai-avatar class="auth-gzh" :src="gzhImage" size="xxl"></ai-avatar>
    <text class="auth-title">申请获取您的以下授权</text>
    <text class="auth-content">获取您的公开信息(昵称、头像、手机等)</text>
    <button v-if="canIUseProfile" class="ai-btn ai-btn--lg ai-btn--block ai-btn--primary" @click="getUserProfile">授权登录</button>
    <button v-else class="ai-btn ai-btn--lg ai-btn--block ai-btn--primary" open-type="getUserInfo" @getuserinfo="mpGetUserInfo">授权登录</button>
    <uni-popup id="getPhoneNumber" ref="getPhoneNumber" type="share">
      <tp-get-phone @mpGetPhoneNumber="mpGetPhoneNumber"></tp-get-phone>
    </uni-popup>
    <button class="ai-btn ai-btn--lg ai-btn--block ai-btn--outline m-t" @click="cancelLogin" >取消</button>
  </view>
</template>

<script>
  import {
    mapState,
    mapMutations,
    mapGetters
  } from 'vuex';

  export default {
    data() {
      return {
        canIUseProfile: false,
        gzhImage: "https://wx.qlogo.cn/mmhead/mONcle9pic3za8PowbfOYsVn0miaiawibibXGdfgeoicBBacmXIt5W7ibeZ4m3XvialSbazYeMRGofUX4HM/0",
      };
    },
    computed: {
      ...mapState({
        hasRegister: state => state.user.hasRegister,
        hasLogin: state => state.user.hasLogin,
        hasPhone: state => state.user.hasPhone,
        hasAvatar: state => state.user.hasAvatar,
      }),
    },
    onLoad(option) {
      if (uni.getUserProfile) {
        this.canIUseProfile = true;
      }
      //console.log("login-page-option:", option);
      if (this.hasLogin && this.hasRegister && this.hasPhone) {
        uni.navigateTo({
          url: "/pages/index/index",
        })
        return;
      }
      if (this.hasLogin && this.hasRegister && !this.hasPhone) {
        this.getPhoneNumber();
        return;
      }
    },
    methods: {
      mpGetUserInfo: function(result) {
        //console.log('[login]mpGetUserInfo', result);
        if (result.detail.errMsg !== 'getUserInfo:ok') {
          uni.showModal({
            title: '获取用户信息失败',
            content: '错误原因' + result.detail.errMsg,
            showCancel: false
          });
          return;
        }
        let user = result.detail.userInfo;
        //console.log("user:", user)
        this.loginAndSaveUser(user);
      },
      getUserProfile() {
        let _that = this;
        uni.getUserProfile({
          desc: '完善用户信息',
          success: function(res) {
            //console.log('[login]getUserProfile', res);
            //_that.$toast(res.errMsg)
            if (res.errMsg !== 'getUserProfile:ok') {
              uni.showModal({
                title: '获取用户信息失败',
                content: '错误原因' + res.errMsg,
                showCancel: false
              });
              return;
            }
            let user = res.userInfo;
            _that.loginAndSaveUser(user);
          },
          fail: function(err) {
            // console.log('[login]getUserProfile-err', err);
            _that.$toast('登录后方可使用');
          }
        })
      },
      loginAndSaveUser(user) {
        let opt = {
          data: {
            nickName: user.nickName,
            userName: user.nickName,
            avatar: user.avatarUrl,
            city: user.city || "",
            country: user.country || "",
            gender: user.gender || "",
            language: user.language || "zh_CN",
            province: user.province || "",
          },
          needAuth: true
        }
        
        //console.log("opt:", opt)
        const saveUserUrl = this.$urls.getApi("saveUser");
        //this.$toast(saveUserUrl)
        this.$store.dispatch('user/login')
        .then(res => {
          //console.log('[login]user-login', res);
          this.$post(saveUserUrl, opt)
          .then(res => {
            //console.log('[login]save-user', res);
            if (!this.hasPhone) {
              this.getPhoneNumber();
              return
            }
            if (!this.hasAvatar) {
              this.nav2ModifyAvatar()
              return
            }
            uni.navigateTo({
              url: "/pages/index/index"
            })
          });
        });
      },
      getPhoneNumber() {
        this.$refs.getPhoneNumber.open();
      },
      nav2ModifyAvatar() {
        uni.navigateTo({
          url: "/pages/login/avatar"
        })
      },
      mpGetPhoneNumber(res) {
        console.log("[login]mpGetPhoneNumber:", res);
        let opt = {
          data: {
            encryptedData: res.detail.encryptedData,
            iv: res.detail.iv,
          },
          needAuth: true
        }
        console.log(res.detail.encryptedData)
        let saveMobileUrl = this.$urls.getApi("saveMobile");
        this.$post(saveMobileUrl, opt).then(res => {
          this.$store.dispatch('user/modifyAuth', {
            hasPhone: true
          });
        });

        if (!this.hasAvatar) {
          this.nav2ModifyAvatar()
          return
        }

        uni.navigateTo({
          url: "/pages/index/index"
        })
      },
      cancelLogin() {
        uni.navigateTo({
          url: "/pages/index/index"
        })
      }
    }
  }
</script>

<style scoped lang="scss">
  @import "@/styles/_button.scss";
  .m-t {
    margin-top: 12px;
  }
  .auth-page {
    background-color: var(--white);
    display: flex;
    flex-direction: column;
    box-sizing: border-box;
    min-height: 100vh;
    align-items: center;
    justify-content: center;
    padding: 0 60rpx 100rpx 60rpx;

    .auth-gzh {
      margin-bottom: 160rpx;
    }

    .auth-title {
      font-size: $font-size-lg;
      font-weight: 400;
      padding-bottom: 40rpx;
    }

    .auth-content {
      font-size: $font-size-lg;
      color: var(--gray-2);
      padding-bottom: 60rpx;
    }
  }
</style>
